package com.clkj.cldisabledmanclient.mvp.myapply;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.clkj.cldisabledmanclient.R;
import com.clkj.cldisabledmanclient.adapter.ListAdapterForYear;
import com.clkj.cldisabledmanclient.adapter.jaylv.JayLvBaseAdapter;
import com.clkj.cldisabledmanclient.adapter.jaylv.ViewHolder;
import com.clkj.cldisabledmanclient.app.CustomApplication;
import com.clkj.cldisabledmanclient.base.BaseActivity;
import com.clkj.cldisabledmanclient.bean.MyApplyBean;
import com.clkj.cldisabledmanclient.constant.Config;
import com.clkj.cldisabledmanclient.constant.ShareKey;
import com.clkj.cldisabledmanclient.constant.TipStr;
import com.clkj.cldisabledmanclient.util.CommonUtil;
import com.clkj.cldisabledmanclient.util.ToastUtil;
import com.clkj.cldisabledmanclient.util.scheduler.SchedulerProvider;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

public class MyApplyListActivity extends BaseActivity implements View.OnClickListener, MyApplyListContract.View , PullToRefreshBase.OnRefreshListener2{


    private RelativeLayout mRlTitle;
    private ImageView mIvBack;
    private TextView mTvTitle;
    private TextView mTvRight;
    private PullToRefreshListView mLv;
    private RelativeLayout mRlEmpty;
    private TextView mTvTipEmpty;
    private TextView mTvYear;

    private ProgressDialog progressDialog;
    private List<MyApplyBean> myApplyBeanList = new ArrayList<>();
    private JayLvBaseAdapter<MyApplyBean> mAdapter;

    private ListView mLvYears;
    private PopupWindow popupWindow;
    private List<String> yearLsit = new ArrayList<>();
    private int statePoition;//选择的单位位置
    /**
     * 刷新标识
     */
    boolean isRefresh = false;
    /**
     * 是否可以加载更多标识
     */
    boolean canLoad = false;
    private Integer mPageIndex = 1;

    private MyApplyListContract.Presenter mPresenter;
    private String idCard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_apply_list);
        initTitle(null, null, "我的申请", true, null);
        initData();
        initView();
        assignView();

        getMyApplyList();
    }

    @Override
    public void initData() {

        idCard = (String) CommonUtil.getShareValue(ShareKey.USER_IDCARD, "");
        mPresenter = new MyApplyListPresenter(this, SchedulerProvider.getInstance(), CustomApplication.getInstance().getHttpService());

        yearLsit.add("2019");
        yearLsit.add("2018");
        yearLsit.add("2017");
        yearLsit.add("2016");
    }

    @Override
    public void assignView() {

        mAdapter = new JayLvBaseAdapter<MyApplyBean>(this, myApplyBeanList, R.layout.item_my_apply) {
            @Override
            public void convert(ViewHolder helper, int position, MyApplyBean item) {

                helper.setText(R.id.tv_applyType, "申请类型：" + item.getType());
                helper.setText(R.id.tv_applyDate, "申请时间：" + item.getApplicationDate());
                helper.setText(R.id.tv_applyState, "当前状态：" + item.getPersonnelCold());
            }
        };

        mLv.setAdapter(mAdapter);

        mLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent toApplyDetail=new Intent(MyApplyListActivity.this,MyApplyDetailActivity.class);
                toApplyDetail.putExtra("personnelId",myApplyBeanList.get(position-1).getPersonnelId());
                startActivity(toApplyDetail);
            }
        });

    }

    @Override
    public void initView() {

        mRlTitle = findViewById(R.id.rl_title);
        mIvBack = findViewById(R.id.iv_back);
        mTvTitle = findViewById(R.id.tv_title);
        mTvRight = findViewById(R.id.tv_right);
        mLv = findViewById(R.id.lv);
        mRlEmpty = findViewById(R.id.rl_empty);
        mTvTipEmpty = findViewById(R.id.tv_tip_empty);
        mTvYear = findViewById(R.id.tv_year);

        mTvYear.setOnClickListener(this);

        mLv.setOnRefreshListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            //选择年份
            case R.id.tv_year:
                // 获取自定义布局文件activity_popupwindow_left.xml的视图
                View popupview = getLayoutInflater().inflate(R.layout.dialog_frag_year, null, false);
                // 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
                //int width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
                int height = getWindowManager().getDefaultDisplay().getHeight();
                popupWindow = new PopupWindow(popupview, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                //设置背景颜色
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                // 设置动画效果
                //popupWindow.setAnimationStyle(R.style.AnimationFade);
                // 这里是位置显示方式,在屏幕的
                //popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
                popupWindow.showAsDropDown(mTvYear);

                popupWindow.update();
                popupWindow.setOnDismissListener(new poponDismissListener());
                //设置背景阴影
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 0.3f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);
                // 点击其他地方消失
                popupview.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        // TODO Auto-generated method stub
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                            popupWindow = null;
                        }
                        return false;
                    }
                });

                mLvYears = (ListView) popupview.findViewById(R.id.lv_years);

                ListAdapterForYear adapterForYear = new ListAdapterForYear(yearLsit, this);
                mLvYears.setAdapter(adapterForYear);
                adapterForYear.setDefSelect(statePoition);
                //筛选年份
                mLvYears.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        statePoition = position;
                        adapterForYear.setDefSelect(position);
                        mTvYear.setText(yearLsit.get(position));
                        popupWindow.dismiss();
                    }
                });

                break;
        }
    }

    @Override
    public void getMyApplyList() {

        mPresenter.getMyApplyList(idCard,
                mPageIndex.toString(),
                Config.DEFAULT_PAGE_SIZE.toString());
    }

    @Override
    public void getMyApplyListSuccess(List<MyApplyBean> myApplyBeans) {


        mLv.onRefreshComplete();

        if (isRefresh) {
            myApplyBeanList.clear();
            isRefresh = false;
        }

        if (myApplyBeans.size() > 0) {

            if (myApplyBeans.size() >= Config.DEFAULT_PAGE_SIZE) {
                mLv.setMode(PullToRefreshBase.Mode.BOTH);
                canLoad = true;
            } else {
                canLoad = false;
                mLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            }
            myApplyBeanList.addAll(myApplyBeans);

        } else {
            canLoad = false;
            mLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);

            if (myApplyBeanList.size() == 0) {
                mLv.setEmptyView(mRlEmpty);
                mTvTipEmpty.setText("未查询到您的康复机构数据");
            } else {
                ToastUtil.showShort(this, TipStr.TIP_NOT_MORE_DATAS);
            }
        }

        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void getMyApplyListError(String tip) {
        mLv.onRefreshComplete();
        if (isRefresh) {
            myApplyBeanList.clear();
            isRefresh = false;
        }
        ToastUtil.showShort(this, tip);
        canLoad = false;
        mLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);

        if (myApplyBeanList.size() == 0) {
            mLv.setEmptyView(mRlEmpty);
        }
    }

    @Override
    public void setPresenter(MyApplyListContract.Presenter presenter) {

    }

    @Override
    public void showLoading() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);
            //设置点击进度对话框外的区域对话框不消失
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setMessage("正在加载...");
            progressDialog.show();
        }
    }

    @Override
    public void dismissLoading() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase pullToRefreshBase) {

        isRefresh=true;
        mPageIndex=1;
        getMyApplyList();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase pullToRefreshBase) {
        mPageIndex++;
        getMyApplyList();
    }

    //window消失的监听
    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 1.0f;
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            getWindow().setAttributes(lp);
        }

    }
}
